/*
 * Copyright 2011 Philippe Blanc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package me.l1k3.fx.client.channel.impl;

import me.l1k3.fx.client.channel.ClipChannel;
import me.l1k3.fx.client.channel.inter.ChannelContext;
import me.l1k3.fx.client.channel.inter.DimensionConstant;

public final class ClipChannelImplJS extends ClipChannel {
    
    @Override
    public final void start(ChannelContext context) { }
    
    @Override
    public final void update(ChannelContext context) {
        double progress = context.getProgress();
        
        int width = getWidth();
        int height = getHeight();
        
        int top = 0;
        int right = width;
        int bottom = height;
        int left = 0;
        
        if(Direction==DimensionConstant.Direction.HORIZONTAL || Direction==DimensionConstant.Direction.BOTH) {
            switch(AnchorHorizontal) {
                case LEFT:
                    right = backward? (int)(progress*width) : (int)((1.0-progress)*width);
                break;
                case CENTER:
                    double half = width/2;
                    right = backward? (int)((progress*half)+half) : (int)(((1.0-progress)*half)+half);
                    left = backward? (int)((1.0-progress)*half) : (int)(progress*half);
                break;
                case RIGHT:
                    left = backward? (int)((1.0-progress)*width) : (int)(progress*width);
                    right = width;
                break;
            }
        }
        
        if(Direction==DimensionConstant.Direction.VERTICAL || Direction==DimensionConstant.Direction.BOTH) {
            switch(AnchorVertical) {
                case TOP:
                    bottom = backward? (int)(progress*height) : (int)((1.0-progress)*height);
                break;
                case CENTER:
                    double half = height/2;
                    bottom = backward? (int)((progress*half)+half) : (int)(((1.0-progress)*half)+half);
                    top = backward? (int)((1.0-progress)*half) : (int)(progress*half);
                break;
                case BOTTOM:
                    top = backward? (int)((1.0-progress)*height) : (int)(progress*height);
                    bottom = height;
                break;
            }
        }
        
        context.getStyle().setProperty("clip", "rect("+top+"px "+right+"px "+bottom+"px "+left+"px)");
    }
}
